class Profile < ActiveRecord::Base
  belongs_to :user
  
  has_attached_file :license,
                    :styles => { :medium => "300x300>",
                                 :thumb => "100x100>"},
                    :path => ":rails_root/public/license/:id/:style_:basename.:extension",
                    :url  => "/license/:id/:style_:basename.:extension"
                    
  attr_protected :license_file_name, :license_size, :license_content_type
  validates_attachment_presence :license, :message => "请上传图片"
  validates_attachment_size :license, :less_than => 5.megabytes, :message => "图片不超过5M"
  validates_attachment_content_type :license, 
                                    :content_type => ['image/jpeg', 'image/pjpeg', 'image/jpg'  ,'image/png','image/bmp','image/gif'], 
                                    :message => "请上传图像文件"
                                 
  validates_presence_of :reg_no, :auth_no, :name,
                        :company, :com_full_address,
                        :zip_code, :tel, :mobile, :pid,
                        :message => "不能为空"
  validates_uniqueness_of :company, :scope => [:user_id,:name]
  before_create :set_address
  def duplicate?
    p = Profile.find_by_user_id_and_name_and_company(user_id,name,company)
    self.id = p.id unless p.nil?
    not p.nil?
  end
  
  def set_address
    province = city = area = ""
    province = Province.find_by_provinceid(self.pid).province unless self.pid.blank?
    city = City.find_by_cityid(self.cid).city unless self.cid.blank?
    area = Area.find_by_areaid(self.aid).area unless self.aid.blank?
    self.com_address = province + city + area
  end
  
  def check_name_and_company(user)
    check_same(user,"name")
    check_same(user,"company")
  end
  
  private
  def check_same(user,attr)
    if attr=="name"
      if( (!user.name.blank?) && (user.name != self.name) )
        errors.add(:name,"与免费注册时不一致")
      end
    elsif attr=="company"
      if( (!user.company.blank?) && (user.company != self.company) )
        errors.add(:company,"与免费注册时不一致")
      end
    end
  end
                                   
end
